package com.zn.loading
{
	import com.zn.bitmapDisplay.BitmapDataFunc;
	import com.zn.bitmapDisplay.BitmapDataUtil;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;

	public class ImageLoader extends LoaderItem
	{
		private var _loader:Loader;
		
		private var _bitmapData:BitmapData;
		_activeTypes("ImageLoader", ImageLoader);
		
		public function ImageLoader(url:String = null, name:String = null)
		{
			super(url, name);
		}
		
		protected override function init():void
		{
			super.init();
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
			_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		protected override function completeHandler(event:Event):void
		{
			super.completeHandler(event);
			
			_bitmapData=BitmapDataUtil.drawBitmapData(_loader.content);
			
			loaderStatus = LoaderStatus.COMPLETED;
			dispatchEvent(new LoaderEvent(LoaderEvent.COMPLETE,this));
		}
		
		public override function load(flush:Boolean = false):void
		{
			if (loaderStatus != LoaderStatus.READY && !flush)
				return;
			
			super.load(flush);
			
			var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
			_loader.load(_urlRequest, context);
		}
		
		public function get displayObject():Bitmap
		{
			return new Bitmap(_bitmapData);
		}
		
		override public function unload():void
		{
			super.unload();
			if (_loader)
			{
				LoaderMax.removeLoaderItem(name, false);
				try
				{
					_loader.unloadAndStop(false);
				} 
				catch(error:Error) 
				{
					
				}
				
				_loader = null;
			}
		}
		
		override public function stop():void
		{
			super.stop();
			if (_loader)
			{
				try
				{
					_loader.close();
				} 
				catch(error:Error) 
				{
					
				}
			}
		}

		public override function pause():void
		{
			super.pause();
			if (_loader)
			{
				try
				{
					_loader.close();
				} 
				catch(error:Error) 
				{
					
				}
			}
		}
	}
}